package com.heima.wemedia.builder;

import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class ArticleDtoBuilder {
    private WmNews wmNews;
    private WmUserMapper wmUserMapper;

    private WmChannelMapper channelMapper;

    private ArticleDto articleDto = new ArticleDto();

    public ArticleDtoBuilder(WmNews wmNews, WmUserMapper wmUserMapper, WmChannelMapper channelMapper) {
        this.wmNews = wmNews;
        this.wmUserMapper = wmUserMapper;
        this.channelMapper = channelMapper;
    }

    /**
     * 属性的拷贝
     */
    public ArticleDtoBuilder buildBeanCopy() {
        BeanUtils.copyProperties(wmNews, articleDto);
        return this;
    }

    /**
     * 构建作者对象到dto
     */
    public ArticleDtoBuilder buildAuthor() {
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorId(wmUser.getId().longValue());
            articleDto.setAuthorName(wmUser.getName());
        }
        return this;
    }

    /**
     * 构建频道对象到dto
     */
    public ArticleDtoBuilder buildChannel() {
        if (null != wmNews.getChannelId()) {
            WmChannel wmChannel = channelMapper.selectById(wmNews.getChannelId());
            articleDto.setChannelName(wmChannel.getName());
        }
        return this;
    }

    //构建基本信息到dto
    public ArticleDtoBuilder buildBasic() {
        articleDto.setLayout(wmNews.getType());
        articleDto.setCreatedTime(new Date());
        articleDto.setCollection(0);
        articleDto.setComment(0);
        articleDto.setViews(0);
        articleDto.setLikes(0);
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        return this;
    }

    //返回dto对象
    public ArticleDto builder(){
        return articleDto;
    }


}
